package com.ncmmall.mall.controller.business.goods;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.GoodsAttributeChannel;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttributeChannel;
import com.ncmmall.domain.business.goods.brand.GoodsBrand;
import com.ncmmall.domain.business.goods.brand.QGoodsBrand;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.goods.image.GoodsImage;
import com.ncmmall.domain.business.goods.unit.GoodsUnit;
import com.ncmmall.domain.business.goods.unit.QGoodsUnit;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.freight.MerchantFreightTemplate;
import com.ncmmall.domain.business.merchant.freight.QMerchantFreightTemplate;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品管理
 *
 * @author linxs
 * @date 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/merchant/goods")
public class GoodsController {

    private final static Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsApplication goodsApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 商品列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Goods goods) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());
        String hql = builderSQL("select u from Goods u where u.merchant.id = :id ", params, goods);
        QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);

        List<GoodsChannel> channels = queryChannelService.findAll("select c.channel from MerchantGoodsChannel c where c.merchant.id = :mid", ImmutableMap.of("mid", Securitys.currentUser().getId()), GoodsChannel.class);
        model.addAttribute("page", page).addAttribute("params", goods).addAttribute("channels", channels);

        return "merchant/goods/list";
    }

    /**
     * 一键代发商品列表
     */
    @RequestMapping(value = "/isIssuingList", method = RequestMethod.GET)
    private String isIssuingList(Model model, QueryPageRequest pageRequest, Goods goods) {

        Map<String, Object> params = new HashMap<>();
        params.put("id", Securitys.currentUser().getId());

        String hql = builderSQL("select u from Goods u where u.merchant.id = :id and u.isIssuingType = 1 ", params, goods);
        QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);

        List<MerchantGoodsChannel> all = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(MapUtil.getLong(params, "id")), MerchantGoodsChannel.class);
        List<GoodsChannel> channels = all.stream().map(MerchantGoodsChannel::getChannel).collect(Collectors.toList());

        model.addAttribute("page", page).addAttribute("params", goods).addAttribute("channels", channels);

        return "merchant/goods/issuing/list";
    }


    /**
     * 查看详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()), GoodsAttribute.class);

        model.addAttribute("goods", goods).addAttribute("attributes", attributes);

        return "merchant/goods/detail";
    }

    /**
     * 修改库存
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/modifyStore", method = RequestMethod.GET)
    private String modifyStore(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()), GoodsAttribute.class);

        model.addAttribute("goods", goods).addAttribute("attributes", attributes);

        return "merchant/goods/modifyStore";
    }

    /**
     * 修改库存
     *
     * @param requestWith
     * @param data
     * @return
     */
    @RequestMapping(value = "/modifyStore", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modifyStore(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("data") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            goodsApplication.modifyStore(data);
            logApplication.eventOfMerchant(Securitys.currentUser(), "修改商品库存信息", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[编辑商品基本信息异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 编辑商品信息
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

        List<GoodsChannel> channels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(goods.getMerchant().getId()), MerchantGoodsChannel.class).stream().map(MerchantGoodsChannel::getChannel).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(goods.getImages())) {
            goods.setImagesData(goods.getImages().stream().map(GoodsImage::getName).collect(Collectors.joining(";")));
        }

        List<GoodsAttribute> attributes;
        if (null != goods.getAttributeChannel()) {
            attributes = queryChannelService.findAll("select r.attribute from GoodsAttributeChannelRelevancy r where r.channel.id = :id ", ImmutableMap.of("id", goods.getAttributeChannel().getId()), GoodsAttribute.class);
        } else {
            attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()).and(QGoodsAttribute.goodsAttribute.status.eq(1)), GoodsAttribute.class);
        }

        List<MerchantFreightTemplate> templates = queryChannelService.findAll(QMerchantFreightTemplate.merchantFreightTemplate.merchant.id.eq(Securitys.currentUser().getId()), MerchantFreightTemplate.class);
        List<GoodsBrand> brands = queryChannelService.findAll(QGoodsBrand.goodsBrand.status.eq(3).and(QGoodsBrand.goodsBrand.merchant.eq(Securitys.currentUser())), GoodsBrand.class);
        List<GoodsUnit> units = queryChannelService.findAll(QGoodsUnit.goodsUnit.status.eq(1).and(QGoodsUnit.goodsUnit.merchant.eq(Securitys.currentUser())), GoodsUnit.class);


        model.addAttribute("_method", "PUT")
                .addAttribute("goods", goods)
                .addAttribute("brands", brands)
                .addAttribute("units", units)
                .addAttribute("templates", templates)
                .addAttribute("channels", channels)
                .addAttribute("attributeChannels", queryChannelService.findAll(QGoodsAttributeChannel.goodsAttributeChannel.id.isNotNull(), GoodsAttributeChannel.class))
                .addAttribute("attributes", attributes);

        return "merchant/goods/form";

    }

    /**
     * 编辑商品基本信息
     */
    @RequestMapping(value = "/{id}/modifyInfo", method = RequestMethod.GET)
    private String modifyInfo(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        List<GoodsChannel> channels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(goods.getMerchant().getId()), MerchantGoodsChannel.class).stream().map(MerchantGoodsChannel::getChannel).collect(Collectors.toList());

        StringBuilder imagesData = new StringBuilder();
        for (GoodsImage image : goods.getImages()) {
            imagesData.append(image.getName());
            imagesData.append(";");
        }

        goods.setImagesData(imagesData.toString());


        List<GoodsAttribute> attributes;
        if (null != goods.getAttributeChannel()) {
            attributes = queryChannelService.findAll("select r.attribute from GoodsAttributeChannelRelevancy r where r.channel.id = :id ", ImmutableMap.of("id", goods.getAttributeChannel().getId()), GoodsAttribute.class);
        } else {
            attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()).and(QGoodsAttribute.goodsAttribute.status.eq(1)), GoodsAttribute.class);
        }

        List<MerchantFreightTemplate> templates = queryChannelService.findAll(QMerchantFreightTemplate.merchantFreightTemplate.merchant.id.eq(Securitys.currentUser().getId()).and(QMerchantFreightTemplate.merchantFreightTemplate.status.eq(1)), MerchantFreightTemplate.class);
        List<GoodsBrand> brands = queryChannelService.findAll(QGoodsBrand.goodsBrand.status.eq(3).and(QGoodsBrand.goodsBrand.merchant.eq(Securitys.currentUser())), GoodsBrand.class);

        List<GoodsUnit> units = queryChannelService.findAll(QGoodsUnit.goodsUnit.status.eq(1).and(QGoodsUnit.goodsUnit.merchant.eq(Securitys.currentUser())), GoodsUnit.class);

        model.addAttribute("_method", "PUT")
                .addAttribute("templates", templates)
                .addAttribute("brands", brands)
                .addAttribute("units", units)
                .addAttribute("goods", goods).addAttribute("channels", channels).addAttribute("attributeChannels", queryChannelService.findAll(QGoodsAttributeChannel.goodsAttributeChannel.id.isNotNull(), GoodsAttributeChannel.class)).addAttribute("attributes", attributes);

        return "merchant/goods/modifyInfo";

    }

    /**
     * 编辑商品基本信息
     */
    @RequestMapping(value = "/{id}/modifyInfo", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modifyInfo(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Goods goods) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            goodsApplication.modifyInfo(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "修改商品信息", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[编辑商品基本信息异常]", e);
            return ImmutableMap.of("status", false);

        }
    }


    /**
     * 编辑商品信息
     *
     * @param requestWith
     * @param goods
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Goods goods) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            goodsApplication.modify(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "修改商品信息", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[编辑商品信息异常]", e);
            return ImmutableMap.of("status", false, "message", "编辑商品异常");
        }
    }

    /**
     * 申请上架
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/applyPutaway", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> applyPutaway(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

            goodsApplication.applyPutaway(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "提交商品上架", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[编辑商品信息异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 批量申请上架
     *
     * @param requestWith
     * @return
     */
    @RequestMapping(value = "/applysPutaway", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> applysPutaway(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            goodsApplication.applysPutaway(Lists.transform(ids, new Function<String, Goods>() {
                @Nullable
                @Override
                public Goods apply(@Nullable String input) {
                    Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(input)), Goods.class);
                    return goods;
                }
            }));

            logApplication.eventOfMerchant(Securitys.currentUser(), "批量提交商品上架", Securitys.getIp(request));


            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量申请上架商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }


    /**
     * 批量下架商品
     *
     * @param requestWith
     * @param data
     * @return
     */
    @RequestMapping(value = "/soldoutss", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> soldoutss(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            goodsApplication.soldoutss(Lists.transform(ids, new Function<String, Goods>() {
                @Nullable
                @Override
                public Goods apply(@Nullable String input) {
                    Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(input)), Goods.class);
                    return goods;
                }
            }));

            logApplication.eventOfMerchant(Securitys.currentUser(), "批量下架商品", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量下架商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 下架商品
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/soldout", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> soldout(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

            goodsApplication.soldout(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "下架商品", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[下架商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 添加商品页面
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {


        WebUser user = Securitys.currentUser();

        Goods goods = new Goods();
        List<GoodsChannel> channels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(Securitys.currentUser().getId()).and(QMerchantGoodsChannel.merchantGoodsChannel.channel.deleteStatus.notIn(1).and(QMerchantGoodsChannel.merchantGoodsChannel.channel.status.eq(1))), MerchantGoodsChannel.class).stream().map(MerchantGoodsChannel::getChannel).collect(Collectors.toList());

        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()).and(QGoodsAttribute.goodsAttribute.status.eq(1)), GoodsAttribute.class);

        List<GoodsAttribute> platformAttributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.parent.isNull().and(QGoodsAttribute.goodsAttribute.status.eq(1)).and(QGoodsAttribute.goodsAttribute.type.eq(1)), GoodsAttribute.class);
        attributes.addAll(platformAttributes);

        List<MerchantFreightTemplate> templates = queryChannelService.findAll(QMerchantFreightTemplate.merchantFreightTemplate.merchant.id.eq(Securitys.currentUser().getId()).and(QMerchantFreightTemplate.merchantFreightTemplate.status.eq(1)), MerchantFreightTemplate.class);
        List<GoodsBrand> brands = queryChannelService.findAll(QGoodsBrand.goodsBrand.status.eq(3).and(QGoodsBrand.goodsBrand.merchant.eq(Securitys.currentUser())), GoodsBrand.class);
        List<GoodsUnit> units = queryChannelService.findAll(QGoodsUnit.goodsUnit.status.eq(1).and(QGoodsUnit.goodsUnit.merchant.eq(user)), GoodsUnit.class);

        model.addAttribute("_method", "POST")
                .addAttribute("goods", goods)
                .addAttribute("templates", templates)
                .addAttribute("brands", brands)
                .addAttribute("channels", channels)
                .addAttribute("units", units)
                .addAttribute("attributeChannels", queryChannelService.findAll(QGoodsAttributeChannel.goodsAttributeChannel.id.isNotNull(), GoodsAttributeChannel.class))
                .addAttribute("attributes", attributes);

        return "merchant/goods/form";
    }

    /**
     * 添加商品
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Goods goods) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }
            goods.setMerchant(Securitys.currentUser());
            goodsApplication.create(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "添加商品", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[添加商品信息异常]", e);
            return ImmutableMap.of("status", false, "message", "添加商品异常");
        }
    }

    /**
     * 删除商品
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

            goodsApplication.remove(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "删除商品", Securitys.getIp(request));

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false);
        }

        return ImmutableMap.of("status", true);

    }


    /**
     * 获取规格的属性值
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/attributes", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> attributeValues(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("result", queryChannelService.findAll(QGoodsAttribute.goodsAttribute.parent.id.eq(id), GoodsAttribute.class));
            data.put("status", true);

            return data;

        } catch (Exception e) {
            logger.error("[查询规格值异常:]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 获取商家的商品规格
     *
     * @param requestWith
     * @return
     */
    @RequestMapping(value = "/goodsAttributes", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> goodsAttributes(@RequestHeader("X-Requested-With") String requestWith) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("result", queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()).and(QGoodsAttribute.goodsAttribute.status.eq(1)), GoodsAttribute.class));
            data.put("status", true);

            return data;

        } catch (Exception e) {
            logger.error("[查询规格值异常:]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 获取二、三级商品类目
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/childChannels", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> middleChannels(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("result", queryChannelService.findAll(QGoodsChannel.goodsChannel.parent.id.eq(id).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0)), GoodsChannel.class));
            data.put("status", true);

            return data;

        } catch (Exception e) {
            logger.error("[查询二级分类异常:]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 获取规格类目关联的规格
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/attributeChannelsRelevancy", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> attributeChannelsRelevancy(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("result", queryChannelService.findAll("select r.attribute from GoodsAttributeChannelRelevancy r where r.channel.id = :id ", ImmutableMap.of("id", id), GoodsAttribute.class));
            data.put("status", true);

            return data;

        } catch (Exception e) {
            logger.error("[查询规格类目关联的规格异常:]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods) {

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
//            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
//            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
//            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }


        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status != 7 ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.defaultPrice " + goods.getOrderByPrice();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.store " + goods.getOrderByStore();
        } else if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }

}
